#!/usr/bin/env python3
from PyQt5.QtCore import QTimer
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QShortcut
from PyQt5.QtGui import QKeySequence
from PyQt5.QtCore import pyqtSignal, QObject
import mainwindow as main_window
import sys
import buttoncb

APP = QtWidgets.QApplication(sys.argv)
MAINWINDOW = QtWidgets.QMainWindow()
UI = main_window.Ui_MainWindow()
UI.setupUi(MAINWINDOW)
QSS_PATH = "./QSS/MacOS.qss"

 # 按下时一直发送命令更新速度显示
def send_command_and_update_lcd(button, command_func, lcd_display):
    """
    当按键按下时，发送指令并更新对应的speed_lcd显示速度
    :param button: 按钮对象
    :param command_func: 发送命令的函数
    :param lcd_display: LCD显示对象
    :param vel: 速度值
    """
    def start_sending_and_update():
        button.timer = QTimer()
        button.timer.timeout.connect(command_func)
        button.timer.start(500)  # 每100ms发送一次命令，可根据需要调整间隔
        command_func()
        vel = buttoncb.vel # 获取当前速度值
        lcd_display.display(vel)  # 更新LCD显示速度

    def stop_sending_and_update():
        if hasattr(button, 'timer'):
            button.timer.stop()
        lcd_display.display(0)  # 松开时将速度显示为0

    button.pressed.connect(start_sending_and_update)
    button.released.connect(stop_sending_and_update)

def button_cb_create():
    # 急停
    UI.all_stop_button.clicked.connect(buttoncb.stop_all_func)
    # 导丝、导管运动
    send_command_and_update_lcd(UI.cath_pull_button, buttoncb.cath_pull_button,UI.cath_speed_lcd)
    send_command_and_update_lcd(UI.cath_push_button, buttoncb.cath_push_button,UI.cath_speed_lcd)
    send_command_and_update_lcd(UI.wire_pull_button, buttoncb.wire_pull_button,UI.wire_speed_lcd)
    send_command_and_update_lcd(UI.wire_push_button, buttoncb.wire_push_button,UI.wire_speed_lcd)
    send_command_and_update_lcd(UI.wire_cw_button, buttoncb.wire_cw_button,UI.wire_rotSpeed_lcd)
    send_command_and_update_lcd(UI.wire_ccw_button, buttoncb.wire_ccw_button,UI.wire_rotSpeed_lcd)
    # 速度挡位
    UI.vel_1.clicked.connect(buttoncb.vel_1_func)
    UI.vel_2.clicked.connect(buttoncb.vel_2_func)
    UI.vel_3.clicked.connect(buttoncb.vel_3_func)
    UI.vel_4.clicked.connect(buttoncb.vel_4_func)
    UI.vel_5.clicked.connect(buttoncb.vel_5_func)

    
def main():
    MAINWINDOW.setStyleSheet(load_stylesheet(QSS_PATH))
    button_cb_create()
    MAINWINDOW.show()
    sys.exit(APP.exec_())

def load_stylesheet(filename):
    """Load and return the stylesheet from a file."""
    with open(filename, "r") as file:
        return file.read()
    
if __name__ == "__main__":
    
    # print("start GUI")
    main()